#include <windows.h>
#include <stdio.h>
#include <time.h>
HANDLE hSlot;
LPTSTR up_lpszSlotName = TEXT("\\\\.\\mailslot\\up_mailslot");

void main()
{   
	DWORD cbWritten;
	time_t rawtime;
	time(&rawtime);
	char timeString[64];
	sprintf_s(timeString,"\\\\.\\mailslot\\down_mailslot_%x",rawtime);
	LPTSTR down_lpszSlotName=TEXT(timeString);
	hSlot = CreateMailslot(
	down_lpszSlotName,		// mailslot 名
	0,							// 不限制消息大小 
	10000,         // 超时10s 
	NULL); 
		
	// 打开mailslot
	HANDLE hFile = CreateFile(up_lpszSlotName, 
		GENERIC_WRITE,		// 可写
		FILE_SHARE_READ,
		(LPSECURITY_ATTRIBUTES) NULL, 
		OPEN_EXISTING,		// 打开一个已经存在的mailslot，应该由服务端已经创建
		FILE_ATTRIBUTE_NORMAL, 
		(HANDLE) NULL); 
	if (hFile == INVALID_HANDLE_VALUE) 
	{ 
		printf("CreateFile failed with %d.\n", GetLastError()); 
		return ; 
	}
	// 向mailslot写入
	char message[100];
	sprintf_s(message,"Hello! Current time is __%x",rawtime);
	LPTSTR lpszMessage=TEXT(message);
	if(!WriteFile(hFile, 
		lpszMessage, 
		(DWORD) (lstrlen(lpszMessage)+1),  
		&cbWritten, 
		(LPOVERLAPPED) NULL)) 
	{ 
		printf("WriteFile failed with %d.\n", GetLastError()); 
		return ; 
	} 
	printf("Slot written to successfully.\n"); 
	CloseHandle(hFile);  // 结束 
	while(1)
	{
		DWORD cbRead;
		TCHAR lpszBuffer[1000]; 
		if(!ReadFile(hSlot,lpszBuffer,1000,&cbRead,NULL))
		{ 
			printf("ReadFile failed with %d.\n", GetLastError());
			int num=15;
			while(num--)
			{
				printf("Close after %d second.\n",num);
				Sleep(1000);
			}
			return; 
		}
		printf("收到 server mailslot 回复: %s\n", lpszBuffer);//显示
	}
}